<template>
  <div class="container">
    <el-form :model="form" label-width="100px">
      <div class="form_box">
        <el-form-item label="用户名" class="name">
          <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="所属角色">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option v-for='item in roleList' :key='item.id' :label='item.roleName' :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="禁用" :value="0"></el-option>
            <el-option label="启用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="form_box">
        <el-form-item label="所属地区" class="area">
          <el-select v-model="form.area">
            <el-option v-for='item in area' :key='item.val' :label='item.name' :value="item.val"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" class="time">
          <el-date-picker v-model="createTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" :default-value="today" value-format='yyyy-MM-dd HH:mm:ss'>
          </el-date-picker>
        </el-form-item>
        <el-form-item class="btn_box">
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
          <el-button type="primary" @click="addAdmin">添加</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" align="center">
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="userName" label="用户名" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newAreaName" label="地区" show-overflow-tooltip></el-table-column>
      <el-table-column prop="roleName" label="所属角色" show-overflow-tooltip></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="updateStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="toLog(scope.row)" type="text" size="small">日志</el-button>
          <el-button type="text" size="small" @click="changeAdmin(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="delAccount(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="form.page" :page-sizes="[10, 20, 30, 40]" :page-size="form.size"
        layout="prev, pager, next, jumper, sizes, total" :total="total">
      </el-pagination>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="30%" :before-close="handleClose" class="elDialog">
      <p slot="title" class="elDialog-header">
        <span>添加/编辑账号</span>
      </p>
      <el-form :model="param" ref='param' :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="param.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="param.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="地区" class="area">
          <el-cascader ref="cascaderResidence" :clearable="true" :options="area"
            :props="{value:'code',label:'name',children:'childVo',checkStrictly:true}" :show-all-levels="false"
            v-model="param.area" placeholder="请选择户籍地" @change="currentResidenceclick">
          </el-cascader>
          <!-- <el-select v-model="param.area">
            <el-option v-for='item in area' :key='item.val' :label='item.name' :value="item.val"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="param.roleId" placeholder="请选择角色">
            <el-option v-for='item in roleList' :key='item.id' :label='item.roleName' :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否管理员">
          <el-radio v-model="param.manager" :label="0">不是</el-radio>
          <el-radio v-model="param.manager" :label="1">是</el-radio>

        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onsubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, changeStatus, addAdmin, changeAdmin, delAdmin, roleList, editInfo, prfindTree } from '../../../api/account';
import { findDictByCode } from '../../../api/index'
import { encrypt } from '../../../utils/unitFile'
export default {
  name: '',
  data () {
    return {
      dialogVisible: false,
      today: null,

      form: {
        page: 1,
        size: 10,
        userName: '',
        roleId: '',
        status: null,
        area: null,
        createStartTime: '',
        createEndTime: ''
      },
      total: 0,
      createTime: '',
      param: {
        roleId: '',
        area: null,
        manager: 0,
        userName: '',
        password: null,
        newAreaName: '',
        newAreaCode: ''
      },
      tableData: [],
      area: [],
      roleList: [],
      rules: {
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        // area: [{ required: true, message: '请选择地区', trigger: 'change' }],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_/.~!@#\$%\^&\-=?\/:;,\(\)"'`|*<>+]+$/, message: '账号由数字、字母符号组成' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_]{6,20}$/, message: '密码由长度为6-20的数字、字母或下划线组成' }
        ]
      }
    };
  },
  created () {
    this.today = new Date() - 30 * 24 * 60 * 60 * 1000;
    // findDictByCode('area').then(res => {
    //   if (res.success) {
    //     let obj = {
    //       name: '',
    //       val: null
    //     }
    //     this.area = res.data.filter(item => item.val !== 553);
    //     this.area.unshift(obj)
    //     console.log(this.area);
    //   } else {
    //     this.$message.error(`${res.msg}`)
    //   }
    // })
    this.prfindTree()
    roleList().then(res => {
      this.roleList = res.data
    })
    this.adminList();
  },
  watch: {
    // 解析创建时间
    createTime: function (val) {
      this.form.createStartTime = val[0];
      this.form.createEndTime = val[1]
      console.log(this.form);
    },

  },
  methods: {
    // 获取管理员列表
    adminList () {
      getList(this.form).then(res => {
        if (res.success) {
          this.tableData = res.data.records || [];
          this.total = res.data.total
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    prfindTree () {
      prfindTree().then(res => {
        if (res.success) {
          this.area = res.data
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    toLog (row) {
      this.$router.push({ path: '/log', query: { userName: row.userName, opeType: 3 } })
    },
    // 重置
    reset () {
      this.form = {
        page: 1,
        size: 10,
        userName: '',
        roleId: '',
        status: null,
        area: null,
        createStartTime: '',
        createEndTime: '',
        // newArea: null
      };
      this.createTime = []
      this.adminList();
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.form.size = val;
      this.adminList();
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.form.page = val;
      this.adminList();
    },
    search () {
      this.adminList();
    },
    // 编辑管理员
    changeAdmin (row) {
      this.rules.password = []
      this.dialogVisible = true;
      editInfo(row.id).then(res => {
        if (res.success) {
          console.log(res);
          this.param = res.data
          this.$set(this.param, 'password', '********')
          if (this.param.area) {
            this.param.newAreaCode = JSON.parse(this.param.newAreaCode)
            this.param.area = this.param.newAreaCode
          } else {
            this.param.newAreaCode = ''
            this.param.newAreaName = ""
          }
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
      // Object.keys(this.param).forEach(item => {
      //   this.param[item] = row[item]
      // })
      console.log(this.param);

      this.id = row.id;
    },
    // 添加管理员
    addAdmin () {
      this.rules.password = [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^[0-9a-zA-Z_]{6,20}$/, message: '密码由长度为6-20的数字、字母或下划线组成' }
      ]
      this.dialogVisible = true;
      this.id = ''
      this.param.area = null;
      this.param.newAreaCode = ''
      this.param.newAreaName = ""
      this.param.id = ""
    },
    // 修改
    onsubmit () {
      this.$refs.param.validate(valid => {
        if (valid) {
          console.log(this.param.password.includes('***'));
          let query = { ...this.param, password: encrypt(this.param.password) }
          if (this.param.password.includes('***')) {
            query.password = null;
          }
          console.log(this.param.area, 'this.param.area')
          if (this.param.area) {
            query.area = this.param.area[this.param.area.length - 1]
            query.newAreaCode = JSON.stringify(this.param.newAreaCode)
          }

          console.log(query);
          (this.id ? changeAdmin(this.id, query) : addAdmin(query)).then(res => {
            console.log(res);
            if (res.success) {
              this.$message.success(`${this.id ? '修改成功' : '添加成功'}`);
              this.adminList();
            } else {
              this.$message.error(`${res.msg}`);
            }
            this.$refs.param.resetFields();
            this.param.area = null;
            this.param.newAreaCode = ''
            this.param.newAreaName = ""
            this.dialogVisible = false;
          });
        }
      });
    },
    handleClose () {
      this.$refs.param.resetFields();
      this.param.area = null;
      this.param.newAreaCode = ''
      this.dialogVisible = false;
    },
    // 删除管理员
    delAccount (row) {
      this.$confirm('您要删除账号，删除后不可恢复，是否确定操作？', '信息提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: action => {
          if (action === 'confirm') {
            delAdmin(row.id).then(data => {
              console.log(data);
              if (data.success) {
                this.$message.success('删除成功');
                this.adminList();
              } else {
                this.$message.error(`${data.msg}`);
              }
            });
          }
        }
      });
    },
    // 修改管理员状态
    updateStatus (row) {
      changeStatus(row.id, row.status).then(data => {
        console.log(data);
      });
    },
    currentResidenceclick (e, form, thsAreaCode) {
      console.log(e, 'e')
      this.$refs.cascaderResidence.dropDownVisible = false;
      if (e.length > 0) {
        thsAreaCode = this.$refs['cascaderResidence'].getCheckedNodes()[0].pathLabels

        this.param.newAreaName = thsAreaCode[thsAreaCode.length - 1]
        this.param.newAreaCode = e
      } else {
        this.param.newAreaName = ''
        this.param.newAreaCode = ''
      }

    },
  }
};
</script>

<style scoped>
.form_box {
    display: flex;
    flex-direction: row;
}
.el-table {
    height: 82%;
}
.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}
.form_box .el-form-item {
    width: 300px;
}
.form_box /deep/ .el-input {
    width: 200px;
}
.form_box /deep/ .el-input__inner {
    width: 200px;
}
/* .form_box .name.el-form-item {
    width: 400px;
} */
.form_box .time.el-form-item {
    width: 600px;
}
/* .form_box .area.el-form-item {
    padding-left: 78px;
    width: 320px !important;
} */
.form_box .time .el-input__inner /deep/ .el-range-input {
    width: 150px !important;
}
.form_box .time /deep/ .el-input__inner {
    width: 400px;
}
.form_box .btn_box {
    float: right;
    width: 400px;
    text-align: right;
}
.form_box .btn_box .el-button {
    width: 85px;
}
.page {
    width: 100%;
    height: 40px;
    background: #ffffff;
    text-align: center;
    padding-top: 20px;
}
.el-dialog .el-form-item /deep/ .el-input__inner {
    width: 100%;
}
.el-dialog .el-form-item /deep/ .el-input {
    width: 100%;
}
.el-dialog .el-form-item /deep/ .el-select {
    width: 100%;
}
.el-dialog .dialog-footer .el-button {
    width: 100px;
    margin-right: 20px;
}
.el-dialog .el-form-item /deep/ .el-input--small .el-input__inner {
    width: 267px;
}
</style>